const path = require('path')
const env = process.env.NODE_ENV
const resolve = (dir) => path.join(__dirname, dir)

const BundleAnalyzerPlugin =
  require('webpack-bundle-analyzer').BundleAnalyzerPlugin
const NodePolyfillPlugin = require('node-polyfill-webpack-plugin')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const ProgressPlugin = require('progress-webpack-plugin')

const Timestamp = new Date().getTime()
process.env.VUE_APP_VERSION = require('./package.json').version

module.exports = {
  publicPath: './', // 根域上下文目录
  outputDir: 'dist', // 构建输出目录
  assetsDir: 'static', // 静态资源目录 (js, style, img, fonts)
  filenameHashing: true, // 生成的静态资源在它们的文件名中包含了 hash 以便更好的控制缓存
  lintOnSave: true, // 是否开启eslint保存检测，有效值：ture | false | 'error'
  runtimeCompiler: true, // 运行时版本是否需要编译
  transpileDependencies: [], // 默认babel-loader忽略mode_modules，这里可增加例外的依赖包名

  chainWebpack: (config) => {
    config.resolve.alias.set('@', resolve('src'))
    config.resolve.extensions.add('.js').add('.vue').add('.json')
  },

  configureWebpack: (config) => {
    config.output.filename = `static/js/[name].[fullhash].bundle.${Timestamp}.js`
    config.output.chunkFilename = `static/js/[name].[fullhash].${Timestamp}.js`

    config.plugins.push(new NodePolyfillPlugin())

    // if (env === 'fsTest' || env === 'yzy-prod-test') {
    //   config.plugins.push(
    //     new BundleAnalyzerPlugin({
    //       analyzerMode: 'disabled', // 不启动展示打包报告的http服务器
    //       generateStatsFile: false // 是否生成stats.json文件
    //     })
    //   )
    // }

    if (env !== 'development') {
      config.optimization.runtimeChunk = {
        name: (entrypoint) => `runtime~${entrypoint.name}`
      }
      config.optimization.splitChunks = {
        chunks: 'all', // 同时分割同步和异步代码,推荐。
        minSize: 100000,
        maxInitialRequests: Infinity,
        automaticNameDelimiter: '_', // 名称分隔符，默认是~
        cacheGroups: {
          // 默认的规则不会打包,需要单独定义
          vendor: {
            test: /[\\/]node_modules[\\/]/,
            name(module) {
              const packageName = module.context.match(
                /[\\/]node_modules[\\/](.*?)([\\/]|$)/
              )[1]
              return `npm.${packageName.replace('@', '')}`
            }
          }
        }
      }

      config.plugins.push(
        new UglifyJsPlugin({
          uglifyOptions: {
            // 生产环境去除console等信息
            compress: {
              // warnings: false, // 若打包错误，则注释这行
              drop_debugger: true, // 是否移除debugger
              drop_console: true,
              pure_funcs: ['console.log'] // 移除console
            }
          },
          sourceMap: false,
          parallel: true
        }),
        new ProgressPlugin()
      )
    }
  },
  parallel: require('os').cpus().length > 1, // 构建时开启多进程处理babel编译
  devServer: {
    open: false,
    // host: '172.18.7.131',
    host: '0.0.0.0',
    port: 8097,
    https: false,
    proxy: {
      '/manage': {
        target: 'http://192.3.17.63/',
        changeOrigin: true
      }
    }
  }
}
